package manager

import android.graphics.Bitmap
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.common.BitMatrix
import com.google.zxing.qrcode.QRCodeWriter
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel

private object QrCode {

    val qrCodeWriter = QRCodeWriter()
    val hintTypeMap = HashMap<EncodeHintType, Any>()

    init {
        hintTypeMap[EncodeHintType.CHARACTER_SET] = "utf-8"
        hintTypeMap[EncodeHintType.MARGIN] = 1
        hintTypeMap[EncodeHintType.ERROR_CORRECTION] = ErrorCorrectionLevel.H
    }
}

private fun deleteWhite(matrix: BitMatrix): BitMatrix {
    val rec = matrix.enclosingRectangle
    val resWidth = rec[2] + 1
    val resHeight = rec[3] + 1
    val resMatrix = BitMatrix(resWidth, resHeight)
    resMatrix.clear()
    for (i in 0 until resWidth) {
        for (j in 0 until resHeight) {
            if (matrix.get(i + rec[0], j + rec[1])) {
                resMatrix.set(i, j)
            }
        }
    }
    return resMatrix
}

fun createQrcodeBitmap(content: String, width: Int, height: Int): Bitmap {
    val matrix = QrCode.qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, QrCode.hintTypeMap)
    val pixel = IntArray(width * height)
    val resMatrix = deleteWhite(matrix)
    val w = resMatrix.width
    val h = resMatrix.height
    for (i in 0 until h) {
        for (j in 0 until w) {
            if (resMatrix.get(j, i)) {
                pixel[i * w + j] = 0x00
            } else {
                pixel[i * w + j] = 0xFFFFFFFF.toInt()
            }
        }
    }
    return Bitmap.createBitmap(pixel, w, h, Bitmap.Config.RGB_565)
}



